import logging
from logging.handlers import TimedRotatingFileHandler
import os
from datetime import datetime, timedelta


class MyLogger:
    def __init__(self, log_dir=None, log_name='app', keep_days=30):
        self.log_dir = log_dir or os.path.join(os.path.dirname(__file__), 'logs')
        self.log_name = log_name
        self.keep_days = keep_days

        if not os.path.exists(self.log_dir):
            os.makedirs(self.log_dir, exist_ok=True)

        log_file = os.path.join(self.log_dir, f"{log_name}.log")
        self.logger = logging.getLogger(log_name)
        self.logger.setLevel(logging.INFO)

        # Timed rotating handler: rotate every midnight, keep backupCount files
        handler = TimedRotatingFileHandler(
            log_file, when='midnight', interval=1, backupCount=keep_days, encoding='utf-8'
        )
        formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

        # 控制台日志
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(formatter)
        self.logger.addHandler(stream_handler)

        # 启动时清理过期日志（兼容Windows、Linux）
        self.cleanup_old_logs()

    def cleanup_old_logs(self):
        """删除超过 keep_days 的日志文件"""
        now = datetime.now()
        for name in os.listdir(self.log_dir):
            if not name.startswith(self.log_name) or not name.endswith('.log'):
                continue
            full_path = os.path.join(self.log_dir, name)
            mtime = datetime.fromtimestamp(os.path.getmtime(full_path))
            if now - mtime > timedelta(days=self.keep_days):
                try:
                    os.remove(full_path)
                except Exception as e:
                    print(f"Failed to remove old log {name}: {e}")

    def info(self, msg):
        self.logger.info(msg)

    def warning(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)

    def debug(self, msg):
        self.logger.debug(msg)

x_logger = MyLogger()